package com.example.backendhjh.service;

import com.example.backendhjh.dto.*;
import com.example.backendhjh.entity.*;
import com.example.backendhjh.exception.ApiException;
import com.example.backendhjh.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrderService {

    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final CartItemMapper cartItemMapper;
    private final ProductMapper productMapper;
    private final UserService userService;

    @Autowired
    public OrderService(OrderMapper orderMapper,
                        OrderItemMapper orderItemMapper,
                        CartItemMapper cartItemMapper,
                        ProductMapper productMapper,
                        UserService userService) {
        this.orderMapper = orderMapper;
        this.orderItemMapper = orderItemMapper;
        this.cartItemMapper = cartItemMapper;
        this.productMapper = productMapper;
        this.userService = userService;
    }

    @Transactional
    public OrderResponseDTO createOrder(OrderDTO orderDTO) {
        // 1. 验证用户存在
        UserResponseDTO user = userService.getUserById(orderDTO.getUserId());
        if (user == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "用户不存在");
        }

        // 2. 创建订单实体
        Order order = new Order();
        order.setOrderNumber(generateOrderNumber());
        order.setUserId(orderDTO.getUserId());
        order.setTotalAmount(BigDecimal.ZERO); // 初始为0，后续计算
        order.setStatus("CREATED");
        order.setCreatedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());
        order.setShippingAddress(orderDTO.getShippingAddress());
        order.setPaymentMethod(orderDTO.getPaymentMethod());

        // 3. 插入订单
        int result = orderMapper.insert(order);
        if (result <= 0) {
            throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "订单创建失败");
        }

        // 4. 处理订单项
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (OrderItemDTO itemDTO : orderDTO.getOrderItems()) {
            // 获取商品信息
            Product product = productMapper.findById(itemDTO.getProductId());
            if (product == null) {
                throw new ApiException(HttpStatus.NOT_FOUND, "商品不存在: " + itemDTO.getProductId());
            }

            // 验证库存
            if (product.getStock() < itemDTO.getQuantity()) {
                throw new ApiException(HttpStatus.BAD_REQUEST,
                        "商品 '" + product.getName() + "' 库存不足. 当前库存: " + product.getStock());
            }

            // 创建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(itemDTO.getProductId());
            orderItem.setQuantity(itemDTO.getQuantity());
            orderItem.setUnitPrice(product.getPrice());
            orderItem.setProductName(product.getName());

            // 插入订单项
            int itemResult = orderItemMapper.insert(orderItem);
            if (itemResult <= 0) {
                throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "添加订单项失败");
            }

            // 更新商品库存
            product.setStock(product.getStock() - itemDTO.getQuantity());
            int updateResult = productMapper.update(product);
            if (updateResult <= 0) {
                throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "更新商品库存失败");
            }

            // 计算小计并累加
            BigDecimal subtotal = product.getPrice().multiply(BigDecimal.valueOf(itemDTO.getQuantity()));
            totalAmount = totalAmount.add(subtotal);
        }

        // 5. 更新订单总金额
        order.setTotalAmount(totalAmount);
        int updateResult = orderMapper.update(order);
        if (updateResult <= 0) {
            throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "更新订单金额失败");
        }

        // 6. 清空购物车
        cartItemMapper.clearCart(orderDTO.getUserId());

        // 7. 返回完整订单信息
        return convertToResponseDTO(order);
    }

    public OrderResponseDTO getOrderById(Long id) {
        Order order = orderMapper.findById(id);
        if (order == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "订单不存在");
        }

        return convertToResponseDTO(order);
    }

    public List<OrderResponseDTO> getOrdersByUser(Long userId) {
        List<Order> orders = orderMapper.findByUserId(userId);
        return orders.stream()
                .map(this::convertToResponseDTO)
                .collect(Collectors.toList());
    }

    public List<OrderResponseDTO> getAllOrders() {
        List<Order> orders = orderMapper.findAll();
        return orders.stream()
                .map(this::convertToResponseDTO)
                .collect(Collectors.toList());
    }

    @Transactional
    public OrderResponseDTO updateOrderStatus(Long orderId, String status) {
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "订单不存在");
        }

        // 验证状态转换
        if (!isValidStatusTransition(order.getStatus(), status)) {
            throw new ApiException(HttpStatus.BAD_REQUEST,
                    "无效的订单状态转换: " + order.getStatus() + " -> " + status);
        }

        // 更新状态和时间
        order.setStatus(status);
        order.setUpdatedAt(LocalDateTime.now());

        int result = orderMapper.update(order);
        if (result <= 0) {
            throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "更新订单状态失败");
        }

        return convertToResponseDTO(order);
    }

    /**
     * 验证订单状态转换是否合法
     */
    private boolean isValidStatusTransition(String currentStatus, String newStatus) {
        // 简单的状态转换验证规则
        switch (currentStatus) {
            case "CREATED":
                return "PAID".equals(newStatus) || "CANCELLED".equals(newStatus);
            case "PAID":
                return "SHIPPED".equals(newStatus) || "CANCELLED".equals(newStatus);
            case "SHIPPED":
                return "COMPLETED".equals(newStatus) || "CANCELLED".equals(newStatus);
            case "COMPLETED":
            case "CANCELLED":
                // 已完成或已取消的订单不能再更改状态
                return false;
            default:
                return false;
        }
    }

    /**
     * 将Order实体转换为OrderResponseDTO
     */
    private OrderResponseDTO convertToResponseDTO(Order order) {
        OrderResponseDTO dto = new OrderResponseDTO();
        dto.setId(order.getId());
        dto.setOrderNumber(order.getOrderNumber());
        dto.setUserId(order.getUserId());

        // 获取用户信息
        UserResponseDTO user = userService.getUserById(order.getUserId());
        if (user != null) {
            dto.setUsername(user.getUsername());
        }

        dto.setTotalAmount(order.getTotalAmount());
        dto.setStatus(order.getStatus());
        dto.setCreatedAt(order.getCreatedAt());
        dto.setUpdatedAt(order.getUpdatedAt());
        dto.setShippingAddress(order.getShippingAddress());
        dto.setPaymentMethod(order.getPaymentMethod());

        // 获取订单项
        List<OrderItem> orderItems = orderItemMapper.findByOrderId(order.getId());
        dto.setOrderItems(orderItems.stream()
                .map(this::convertToItemResponseDTO)
                .collect(Collectors.toList()));

        return dto;
    }

    /**
     * 将OrderItem实体转换为OrderItemResponseDTO
     */
    private OrderItemResponseDTO convertToItemResponseDTO(OrderItem item) {
        OrderItemResponseDTO dto = new OrderItemResponseDTO();
        dto.setId(item.getId());
        dto.setOrderId(item.getOrderId());
        dto.setProductId(item.getProductId());
        dto.setProductName(item.getProductName());

        // 获取商品图片
        Product product = productMapper.findById(item.getProductId());
        if (product != null) {
            dto.setProductImage(product.getImageUrl());
        }

        dto.setQuantity(item.getQuantity());
        dto.setUnitPrice(item.getUnitPrice());
        dto.setSubtotal(item.getUnitPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
        return dto;
    }

    /**
     * 生成唯一订单号
     */
    private String generateOrderNumber() {
        // 格式: ORD-年月日-随机码
        String datePart = LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
        String randomPart = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
        return "ORD-" + datePart + "-" + randomPart;
    }
}